package com.eightbears.beboy.base;

import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.easemob.redpacketsdk.RPInitRedPacketCallback;
import com.easemob.redpacketsdk.RPValueCallback;
import com.easemob.redpacketsdk.RedPacket;
import com.easemob.redpacketsdk.bean.RedPacketInfo;
import com.easemob.redpacketsdk.bean.TokenData;
import com.easemob.redpacketsdk.constant.RPConstant;
import com.eightbears.beboy.base.cache.BaseCache;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.view.image.view.CropImageView;
import com.eightbears.beboy.base.view.image.view.GlideImageLoader;
import com.eightbears.beboy.base.view.image.view.ImagePicker;
import com.eightbears.beboy.ui.chat.DemoHelper;
import com.eightbears.greendao.DaoMaster;
import com.eightbears.greendao.DaoSession;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.umeng.analytics.MobclickAgent;
import com.yixia.camera.VCamera;

import java.io.File;

import cn.jiguang.share.android.api.JShareInterface;

import static com.eightbears.beboy.base.util.CommonAPI.CAHCE_VIDEO_FILE;


/**
 * Created by baoga on 2017/7/2.
 */
public class BaseApplication extends MultiDexApplication {

    public static String VIDEO_PATH = CAHCE_VIDEO_FILE;

    private static DaoMaster daoMaster;
    private static DaoSession daoSession;
    private static Context applicationContext;
    private static BaseApplication instance;

    /**
     * 友盟注册
     */
//     {
//        PlatformConfig.setWeixin("wx52064d18c1389f26", "9e1c043ab8a99bd7d34a39557bb8dfd4");
//    }

    @Override
    public void onCreate() {
        super.onCreate();
        initApplication();
        initChat();
        initVideo();
    }

    private void initChat(){
        DemoHelper.getInstance().init(applicationContext);
        RedPacket.getInstance().initRedPacket(applicationContext, RPConstant.AUTH_METHOD_EASEMOB, new RPInitRedPacketCallback() {

            @Override
            public void initTokenData(RPValueCallback<TokenData> callback) {
                TokenData tokenData = new TokenData();
                tokenData.imUserId = EMClient.getInstance().getCurrentUser();
                //此处使用环信id代替了appUserId 开发者可传入App的appUserId
                tokenData.appUserId = EMClient.getInstance().getCurrentUser();
                tokenData.imToken = EMClient.getInstance().getAccessToken();
                //同步或异步获取TokenData 获取成功后回调onSuccess()方法
                callback.onSuccess(tokenData);
            }

            @Override
            public RedPacketInfo initCurrentUserSync() {
                //这里需要同步设置当前用户id、昵称和头像url
                String fromAvatarUrl = "";
                String fromNickname = EMClient.getInstance().getCurrentUser();
                EaseUser easeUser = EaseUserUtils.getUserInfo(fromNickname);
                if (easeUser != null) {
                    fromAvatarUrl = TextUtils.isEmpty(easeUser.getAvatar()) ? "none" : easeUser.getAvatar();
                    fromNickname = TextUtils.isEmpty(easeUser.getNick()) ? easeUser.getUsername() : easeUser.getNick();
                }
                RedPacketInfo redPacketInfo = new RedPacketInfo();
                redPacketInfo.fromUserId = EMClient.getInstance().getCurrentUser();
                redPacketInfo.fromAvatarUrl = fromAvatarUrl;
                redPacketInfo.fromNickName = fromNickname;
                return redPacketInfo;
            }
        });
        RedPacket.getInstance().setDebugMode(true);
    }

    private void initApplication() {
        JShareInterface.setDebugMode(true);
        JShareInterface.init(this);
        MobclickAgent.setSessionContinueMillis(300000);
        applicationContext = this;
        instance = this;
        MultiDex.install(this);
        SPUtil.initSharedPreference(this);
        initImagePicker();
    }

    /**
     * 设置视频缓存
     */
    private void initVideo() {
        VIDEO_PATH += String.valueOf(System.currentTimeMillis());
        File file = new File(VIDEO_PATH);
        if (!file.exists()) file.mkdirs();
        VCamera.setVideoCachePath(VIDEO_PATH);
        VCamera.setDebugMode(false);
        VCamera.initialize(this);
    }

    public static Context getContext() {

        return applicationContext;
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(9);                         //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    /**
     * 数据库帮助类
     *
     * @param context
     * @return
     */
    public static DaoMaster getDaoMaster(Context context) {
        if (daoMaster == null) {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, BaseCache.DB_NAME, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    public static DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }


    public static BaseApplication getInstance() {
        return instance;
    }
}


